{% extends "base.html" %}

{% block title %}设备出库{% endblock %}

{% block content %}
<div class="container-xl py-4">
    <h2 class="page-title">设备出库</h2>
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-arrow-up me-2"></i>设备出库</h5>
                </div>
                <div class="card-body">
                    <!-- SN码输入区域 -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">输入SN码</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="sn" class="form-label">SN码</label>
                                        <input type="text" class="form-control" id="sn" placeholder="请输入SN码">
                                    </div>
                                    <button type="button" class="btn btn-primary" onclick="addSn()">添加</button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">批量导入</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="csvFile" class="form-label">CSV文件</label>
                                        <input type="file" class="form-control" id="csvFile" accept=".csv">
                                    </div>
                                    <button type="button" class="btn btn-primary" onclick="importSn()">导入</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- SN码列表 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">待查询SN码列表</h6>
                        </div>
                        <div class="card-body">
                            <div id="snList" class="mb-3">
                                <!-- SN码列表将在这里动态生成 -->
                            </div>
                            <button type="button" class="btn btn-primary" onclick="searchEquipment()">查询设备</button>
                        </div>
                    </div>

                    <!-- 查询结果 -->
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">查询结果</h6>
                        </div>
                        <div class="card-body">
                            <div id="searchResult" class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th><input type="checkbox" id="selectAll" onchange="toggleSelectAll()"></th>
                                            <th>入库时间</th>
                                            <th>SN码</th>
                                            <th>型号</th>
                                            <th>生产厂商</th>
                                            <th>原网元名称</th>
                                            <th>现网元名称</th>
                                            <th>设备类型</th>
                                            <th>制式</th>
                                            <th>状态</th>
                                            <th>出库时间</th>
                                        </tr>
                                    </thead>
                                    <tbody id="equipmentList">
                                        <!-- 查询结果将在这里动态生成 -->
                                    </tbody>
                                </table>
                            </div>
                            <div id="searchStatus" class="mt-3">
                                <!-- 查询状态信息将在这里显示 -->
                            </div>
                            <button type="button" class="btn btn-success mt-3" id="confirmOutbound" onclick="confirmOutbound()" disabled>确认出库</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 出库确认对话框 -->
    <div class="modal fade" id="outboundModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认出库</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确认要将选中的设备出库吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmOutboundBtn">确认出库</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let snList = [];
    let selectedEquipment = [];

    // 添加SN码
    function addSn() {
        const sn = document.getElementById('sn').value.trim();
        if (sn) {
            if (!snList.includes(sn)) {
                snList.push(sn);
                updateSnList();
                document.getElementById('sn').value = '';
            } else {
                alert('该SN码已添加');
            }
        }
    }

    // 导入CSV文件
    function importSn() {
        const file = document.getElementById('csvFile').files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const lines = e.target.result.split('\n');
                lines.forEach(line => {
                    const sn = line.trim();
                    if (sn && !snList.includes(sn)) {
                        snList.push(sn);
                    }
                });
                updateSnList();
            };
            reader.readAsText(file);
        }
    }

    // 更新SN码列表显示
    function updateSnList() {
        const snListElement = document.getElementById('snList');
        snListElement.innerHTML = '';
        snList.forEach((sn, index) => {
            const badge = document.createElement('span');
            badge.className = 'badge bg-primary me-2 mb-2';
            badge.innerHTML = `
                ${sn}
                <button type="button" class="btn-close btn-close-white ms-2" 
                        style="font-size: 0.5rem;" onclick="removeSn(${index})"></button>
            `;
            snListElement.appendChild(badge);
        });
    }

    // 移除SN码
    function removeSn(index) {
        snList.splice(index, 1);
        updateSnList();
    }

    // 查询设备
    function searchEquipment() {
        if (snList.length === 0) {
            alert('请先添加SN码');
            return;
        }

        document.getElementById('searchStatus').innerHTML = '<div class="alert alert-info">正在查询...</div>';
        document.getElementById('equipmentList').innerHTML = '';
        document.getElementById('confirmOutbound').disabled = true;

        fetch('/search_equipment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ sn_list: snList })
        })
        .then(response => response.json())
        .then(response => {
            if (response.success) {
                if (response.equipment.length > 0) {
                    const equipmentList = document.getElementById('equipmentList');
                    response.equipment.forEach(equipment => {
                        // 格式化入库时间
                        let formattedDate = equipment.date;
                        if (formattedDate && formattedDate.includes('T')) {
                            formattedDate = formattedDate.replace('T', ' ');
                        }
                        equipmentList.innerHTML += `
                            <tr>
                                <td><input type="checkbox" class="equipment-checkbox" 
                                         data-sn="${equipment.sn}" onchange="updateSelectedEquipment()"></td>
                                <td>${formattedDate}</td>
                                <td>${equipment.sn}</td>
                                <td>${equipment.model}</td>
                                <td>${equipment.manufacturer}</td>
                                <td>${equipment.original_network_element || equipment.network_element}</td>
                                <td>${equipment.current_network_element || ''}</td>
                                <td>${equipment.type}</td>
                                <td>${equipment.standard}</td>
                                <td>${equipment.status}</td>
                                <td>${equipment.outbound_time || ''}</td>
                            </tr>
                        `;
                    });
                    document.getElementById('confirmOutbound').disabled = false;
                    document.getElementById('searchStatus').innerHTML = '<div class="alert alert-success">查询成功</div>';
                } else {
                    document.getElementById('searchStatus').innerHTML = '<div class="alert alert-warning">未找到符合条件的设备</div>';
                }
            } else {
                document.getElementById('searchStatus').innerHTML = `<div class="alert alert-danger">${response.message}</div>`;
            }
        })
        .catch(error => {
            document.getElementById('searchStatus').innerHTML = '<div class="alert alert-danger">查询失败，请稍后重试</div>';
        });
    }

    // 全选/取消全选
    function toggleSelectAll() {
        const checkboxes = document.getElementsByClassName('equipment-checkbox');
        const selectAll = document.getElementById('selectAll');
        Array.from(checkboxes).forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
        updateSelectedEquipment();
    }

    // 更新选中的设备
    function updateSelectedEquipment() {
        selectedEquipment = [];
        const checkboxes = document.getElementsByClassName('equipment-checkbox');
        Array.from(checkboxes).forEach(checkbox => {
            if (checkbox.checked) {
                selectedEquipment.push(checkbox.dataset.sn);
            }
        });
        document.getElementById('confirmOutbound').disabled = selectedEquipment.length === 0;
    }

    // 获取选中的设备
    function getSelectedEquipment() {
        const checkboxes = document.getElementsByClassName('equipment-checkbox');
        const selectedSn = [];
        Array.from(checkboxes).forEach(checkbox => {
            if (checkbox.checked) {
                selectedSn.push(checkbox.dataset.sn);
            }
        });
        return selectedSn;
    }

    // 确认出库
    function confirmOutbound() {
        const selectedSn = getSelectedEquipment();
        if (selectedSn.length === 0) {
            alert('请选择要出库的设备');
            return;
        }
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('outboundModal'));
        modal.show();
    }

    // 确认出库按钮点击事件
    document.getElementById('confirmOutboundBtn').addEventListener('click', function() {
        const selectedSn = getSelectedEquipment();
        console.log('准备出库，选中SN:', selectedSn);
        if (selectedSn.length === 0) {
            alert('请选择要出库的设备');
            return;
        }

        fetch('/outbound_equipment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                sn_list: selectedSn
            })
        })
        .then(response => response.json())
        .then(response => {
            console.log('出库接口响应:', response);
            if (response.success) {
                alert(response.message);
                if (response.warning) {
                    alert(response.warning);
                }
                // 清空SN码列表和表格
                snList = [];
                updateSnList();
                document.getElementById('equipmentList').innerHTML = '';
                document.getElementById('searchStatus').innerHTML = '';
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('outboundModal'));
                modal.hide();
            } else {
                alert(response.message);
            }
        })
        .catch(error => {
            console.error('出库接口异常:', error);
            alert('出库失败，请稍后重试');
        });
    });
</script>
{% endblock %} 